package pswvclass.pswvandroid2.com.risk;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pswvclass.pswvandroid2.R;
import pswvclass.pswvandroid2.com.kwords.KwordList;
import pswvclass.pswvandroid2.com.po.Risk;
import pswvclass.pswvandroid2.com.util.HttpUtils;

/**
 * Created by Administrator on 2018/11/4.
 */
public class RiskSee extends Fragment implements View.OnClickListener {
    private String tag = "RiskSee";
    private TextView kWords;
    private ListView listView;
    private TextView risk_id;
    private TextView risk_context;
    MyAdapter my;
    protected static final int NO_ADD = 2;
    protected static final int SUCCESS = 0;
    protected static final int ERROR = 1;
    protected static final int DELE_SUCCESS = 3;
    protected static final int DELE_SUCCESS1 = 7;
    protected static final int SEE_SUCCESS = 4;
    protected static final int EDIT_SUCCESS = 5;
    protected static final int RISKSEARCH_SUCCESS = 6;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.pswv_risk_see, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            String data = bundle.getString("data");
            String kWords1 = bundle.getString("kWord");
            List<Risk> datas1 = new ArrayList<Risk>();
            try {
                JSONArray ja = new JSONArray(data);
                kWords = (TextView) getView().findViewById(R.id.see_kwords);
                kWords.setText("关于" + kWords1 + "风险经验");
                for (int i = 0; i < ja.length(); i++) {
                    JSONObject temp = (JSONObject) ja.get(i);
                    Risk r = new Risk();
                    r.setRiskId(temp.getInt("riskId"));
                    r.setKWords(temp.getString("kWord"));
                    r.setContent(temp.getString("content"));
                    datas1.add(r);
                }
                my = new MyAdapter(getContext(), datas1);
                listView = (ListView) getView().findViewById(R.id.pswv_risk_list1);
                listView.setAdapter(my);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    break;
                case RISKSEARCH_SUCCESS:
                    break;
                case ERROR:
                    Toast.makeText(getContext(), "连接错误 ....", Toast.LENGTH_SHORT).show();
                    break;
                case NO_ADD:
                    Toast.makeText(getContext(), " 没有查询到....", Toast.LENGTH_SHORT).show();
                    break;
                case DELE_SUCCESS1:
                    my.notifyDataSetChanged();
                    break;
                case DELE_SUCCESS:
                    final List l = (List) msg.obj;
                    final Risk r = (Risk) l.get(0);
                    final List<Risk> datas = (List<Risk>) l.get(1);
                    new Thread() {
                        public void run() {
                            try {
                                HttpUtils hu = new HttpUtils();
                                String data2;
                                final String src = getResources().getString(R.string.src_mysql) + "pswv/api/riskAction/remove";
                                final Map<String, String> map1 = new HashMap<String, String>();
                                map1.put("id", r.getkRiskId() + "");
                                data2 = hu.submitPostData(src, map1, "utf-8");
                                JSONObject jsonObj = new JSONObject(data2);
                                int result = Integer.parseInt(jsonObj.getString("code"));
                                if (result == 0) {
                                    datas.remove(r);
                                    Message msg = Message.obtain();
                                    msg.what = DELE_SUCCESS1;
                                    mHandler.sendMessage(msg);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                Log.v(tag, e + "");
                            }
                        }
                    }.start();
                    break;
                case SEE_SUCCESS:
                    try {
                        JSONObject data = (JSONObject) msg.obj;
                        RiskSee rs = new RiskSee();
                        Bundle bundle = new Bundle();
                        bundle.putString("kWord", data.getString("kWord"));
                        bundle.putString("content", data.getString("content"));
                        rs.setArguments(bundle);
                        getFragmentManager()
                                .beginTransaction()
                                .addToBackStack(null)
                                .replace(R.id.realtabcontent, rs).commit();

                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.v(tag, e + "");
                    }
                    break;
                case EDIT_SUCCESS:
                    try {
                        JSONObject data = (JSONObject) msg.obj;
                        RiskEdit re = new RiskEdit();
                        Bundle bundle = new Bundle();
                        bundle.putInt("editid", data.getInt("id"));
                        bundle.putString("kWord", data.getString("kWord"));
                        bundle.putString("content", data.getString("content"));
                        re.setArguments(bundle);
                        getFragmentManager()
                                .beginTransaction()
                                .addToBackStack(null)
                                .replace(R.id.realtabcontent, re).commit();

                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.v(tag, e + "");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            default:
                break;
        }
    }

    class MyAdapter extends BaseAdapter implements AdapterView.OnItemClickListener {
        private LayoutInflater mInflater;
        private List<Risk> datas;

        public MyAdapter(Context context, List<Risk> contentList) {
            this.mInflater = LayoutInflater.from(context);
            this.datas = contentList;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int position) {

            return datas.get(position);
        }

        @Override
        public long getItemId(int position) {

            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(getContext(), R.layout.pswv_risk_list_see, null);
            risk_id = (TextView) view.findViewById(R.id.risk_id);
            risk_context = (TextView) view.findViewById(R.id.risk_context);
            Risk r = datas.get(position);
            risk_id.setText(String.valueOf(datas.get(position).getkRiskId()));
            risk_context.setText(datas.get(position).getContent());
            ((ListView) parent).setOnItemClickListener(this);
            return view;
        }

        private void showDialog() {

        }

        @Override
        public void onItemClick(AdapterView<?> adapterView, final View view, final int i, long l) {
            PopupMenu popup = new PopupMenu(getContext(), view);
            MenuInflater inflater = popup.getMenuInflater();
            inflater.inflate(R.menu.risk_meun, popup.getMenu());
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    //当点击时弹出被点击象标题

                    switch (item.getItemId()) {
                        case R.id.risk_del:
                            final Risk r = datas.get(i);
                            AlertDialog.Builder bb = new AlertDialog.Builder(getContext());
                            bb.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int b) {
                                    List<Object> l = new ArrayList<Object>();
                                    l.add(r);
                                    l.add(datas);
                                    Message msg = Message.obtain();
                                    msg.obj = l;
                                    msg.what = DELE_SUCCESS;
                                    mHandler.sendMessage(msg);
                                }
                            });
                            bb.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();
                                }
                            });
                            bb.setMessage("确定要删除吗？");
                            bb.setTitle("提示");
                            bb.show();
                            break;
                        case R.id.risk_edit:
                            final Risk r2 = datas.get(i);
                            new Thread() {
                                @Override
                                public void run() {
                                    try {
                                        HttpUtils hu = new HttpUtils();
                                        String data2;
                                        final String src = getResources().getString(R.string.src_mysql) + "pswv/api/riskAction/queryById";
                                        final Map<String, String> map1 = new HashMap<String, String>();
                                        map1.put("id", r2.getkRiskId() + "");
                                        data2 = hu.submitPostData(src, map1, "utf-8");
                                        JSONObject jsonObj = new JSONObject(data2);
                                        JSONObject jsonObj1 = jsonObj.getJSONObject("response");
                                        int result = Integer.parseInt(jsonObj.getString("code"));
                                        if (result == 0) {
                                            Message msg = Message.obtain();
                                            msg.obj = jsonObj1;
                                            msg.what = EDIT_SUCCESS;
                                            mHandler.sendMessage(msg);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        Log.v(tag, e + "");
                                    }
                                }
                            }.start();
                            break;
                        case R.id.risk_see:

                            final Risk r1 = datas.get(i);
                            new Thread() {
                                @Override
                                public void run() {
                                    try {
                                        HttpUtils hu = new HttpUtils();
                                        String data2;
                                        final String src = getResources().getString(R.string.src_mysql) + "pswv/api/riskAction/queryById";
                                        final Map<String, String> map1 = new HashMap<String, String>();
                                        map1.put("id", r1.getkRiskId() + "");
                                        data2 = hu.submitPostData(src, map1, "utf-8");
                                        JSONObject jsonObj = new JSONObject(data2);
                                        JSONObject jsonObj1 = jsonObj.getJSONObject("response");
                                        int result = Integer.parseInt(jsonObj.getString("code"));
                                        if (result == 0) {
                                            Message msg = Message.obtain();
                                            msg.obj = jsonObj1;
                                            msg.what = SEE_SUCCESS;
                                            mHandler.sendMessage(msg);
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        Log.v(tag, e + "");
                                    }
                                }
                            }.start();
                            break;
                        default:
                            break;
                    }
                    return true;
                }
            });
            popup.show();
        }

    }
}
